package com.ruoyi.web.controller.api;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.params.CustomerCounterListParams;
import com.ruoyi.system.domain.params.CustomerOrderListParams;
import com.ruoyi.system.domain.vo.CustomerCounterListVo;
import com.ruoyi.system.domain.vo.CustomerInfo;
import com.ruoyi.system.domain.vo.CustomerOrderList;
import com.ruoyi.system.service.CustomerService;
import com.ruoyi.system.service.IWhCounterService;
import com.ruoyi.system.service.impl.CustomerServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Author: ChenHaiDong
 * @CreateTime: 2023-03-01  16:08
 * @Description: TODO 客户端接口
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/customer/api")
public class CustomerController extends BaseController {

    @Resource
    private RedisCache redisCache;
    @Resource
    private CustomerService customerService;
    @Resource
    private IWhCounterService counterService;

    /**
     * 获取当前登录用户
     * @return
     */
    public Integer getUid() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new ServiceException("token no avail",207);
        }
        String tokenKey = String.format(CustomerServiceImpl.USER_TOKEN_KEY, token);
        Object cacheObject = redisCache.getCacheObject(tokenKey);
        if (ObjectUtils.isEmpty(cacheObject)) {
            throw new ServiceException("token no avail",207);
        }
        // token 续期,小于5小时自动续期 24 小时
        long expire = redisCache.getExpire(tokenKey);
        if (expire <= 60 * 60 * 5) {
            redisCache.expire(tokenKey,60 * 60 * 24);
        }
        return Integer.parseInt(String.valueOf(cacheObject));
    }

    /**
     * 客户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody Map<String,Object> user) {
        if (null == user || MapUtils.isEmpty(user)) {
            return AjaxResult.error("invalid parameter");
        }
        String account = MapUtils.getString(user,"account","");
        String password = MapUtils.getString(user,"password","");
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
            return AjaxResult.error("password error");
        }
        try {
            String login = customerService.login(account, password);
            return AjaxResult.success("login success",login);
        } catch (Exception e) {
            log.error("客户登录失败：{}",e.getMessage());
            return AjaxResult.error("password error");
        }
    }

    /**
     * 客户退出登录
     * @return
     */
    @GetMapping("/loginout")
    public AjaxResult loginout(HttpServletRequest request) {
        try {
            getUid();
            String token = request.getHeader("token");
            redisCache.deleteObject(String.format(CustomerServiceImpl.USER_TOKEN_KEY,token));
            return success();
        }catch (Exception e) {
            log.error("退出登录发生错误：{}",e.getMessage());
            return success();
        }
    }

    /**
     * 客户端获取用户详情
     * @return
     */
    @GetMapping("/user/info")
    public AjaxResult getTokenInfo() {
        try {
            CustomerInfo userInfo = customerService.getUserInfoById(getUid());
            if (userInfo == null) {
                return AjaxResult.error("user does not exist");
            }
            return AjaxResult.success("获取成功", userInfo);
        }catch (Exception e) {
            log.error("客户端获取用户详情发生错误：{}",e.getMessage());
            return AjaxResult.error("Failed to get user details");
        }
    }

    /**
     * 获取客户订单列表
     * @param params
     * @return
     */
    @GetMapping("/order/list")
    public TableDataInfo findCustomerOrderList(CustomerOrderListParams params) {
        params.setCustomerId(getUid());
        startPage();
        List<CustomerOrderList> list = customerService.findCustomerOrderList(params);
        return getDataTable(list);
    }

    /**
     * 获取客户货柜列表
     * @param params
     * @return
     */
    @GetMapping("/counter/list")
    public TableDataInfo findCustomerCounter(CustomerCounterListParams params) {
        params.setCustomerId(getUid());
        startPage();
        List<CustomerCounterListVo> list = counterService.findCustomerCounter(params);
        return getDataTable(list);
    }

}
